#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "JiangHu"

# 将其他项目根目录添加到 sys.path
from django.shortcuts import render,redirect;
from django.http import JsonResponse;
from common.PageVo import *;
import json;
from common.md5_util import *;
from django.db.models import Q;
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage;
from app_spider.models import *;
from datetime import datetime;
from dcb_application import *;
from data_process.dcb_forecast import *;

'''
Spider app service
'''

def get_dcbs(request):
    if request.method == "POST":
        search = Search_Vo(json.loads(request.body));
        print(search.__dict__);
        # 使用 keyword 进行模糊匹配
        dcbs = Double_Color_Ball_1.objects\
            .filter(Q(issue_no__icontains=search.keyword)).order_by(search.sort);

        paginator = Paginator(dcbs, search.page_size);
        try:
            dcbs = paginator.page(search.current_page);
        except PageNotAnInteger as e:
            search.current_page = 1;
            dcbs = paginator.page(1);
        except EmptyPage as e:
            search.current_page= paginator.num_pages;
            dcbs = paginator.page(search.current_page);

        dcb_list = list(user.dcb_dict() for user in dcbs);
        return JsonResponse(Page_Info(
            total=paginator.count,
            pages=paginator.num_pages,
            current_page=search.current_page,
            page_size=search.page_size,
            list=dcb_list
        ).result());
    else:
        return JsonResponse(Result(500, "Unsurport request method.").result());

# dcb table page
def dcbs_page(request):
    content = {};
    # 页面路径以 templates 文件夹为根
    return render(request, "spider/dcbs.html", content);

# 跟新 100 期
def update_dcbs(request, number):
    if request.method == "GET":
        # TODO 调用 whgc 项目相应模块，进行数据爬取
        spider_application(int(number) // 20);

        return JsonResponse(Result(200, "更新成功").result());
    else:
        return JsonResponse(Result(500, "Unsurport request method.").result());

#预测
def update(request):
    if request.method == "GET":
        random_list = get_random_forecast();   # 随机预测
        df = init_dcb_df_data(get_all_dcb());
        ses_list = get_ses_forecast(df);   #平滑指数预测
        holt_list = get_holt_forecast(df);  #霍尔特预测

        # print(random_list)
        # print(ses_list)
        # print(holt_list)

        a = "随机预测：%s\n平滑指数预测：%s\n霍尔特预测：%s" % (random_list, ses_list, holt_list)
        # a = get_random_forecast();

        return JsonResponse(Result(200, "ss", a).result());
    else:
        return JsonResponse(Result(500, "Unsurport request method.").result());

